#ifndef SERVER_H
#define SERVER_H

#include <QMutex>
#include <QTcpServer>
#include "player.h"
#include "..\Common\common.h"

class Server : public QTcpServer
{
    Q_OBJECT
public:
    //单例类
    static Server* getInstance() {
        static Server m;
        return &m;
    }

    bool Start(int port); //服务器开启

    //统计某个房间内的玩家数
    int CountPlayersInRoom(int room);
    void CountPlayersInRoom(int room, ROOM_STATE& s);

    //查询玩家
    Player* Find(const QString name);

    //新增玩家
    bool Add(Player* p);

    //删除玩家
    bool Remove(const QString name);  //根据名字查
    bool Remove(Player* p);           //根据玩家对象查

    void CheckHeartbeat();               //检查心跳
    void UpdateRoomState();              //向所有在线玩家发送当前所有房间人数状态

protected:
    void timerEvent(QTimerEvent* e);


signals:
    void sigLog(QString text);                    //日志信号

public slots:
    void slotNewConnection();                     //newConnection的槽函数
    void slotRecvMsg(char* pData, int nDataLen);  //接收消息槽函数

private:
    explicit Server(QObject *parent = nullptr);

    //处理接收到的玩家TCP消息
    void OnMsg(Player* p, MSG_HEADER* pHeader, char *pData, int nDataLen); //处理接收到的玩家TCP消息
    void OnMsgLogon(Player* player, MSG_HEADER *pHeader);                  //客户端玩家申请登陆
    void OnMsgHeartBeat(Player* player, MSG_HEADER* pHeader);
    void OnMsgSay(Player* player, MSG_HEADER* pHeader);
    void OnMsgMove(Player* player, MSG_HEADER* pHeader);                   //客户端五子棋走棋
    void OnMsgMoveCC(Player* player, MSG_HEADER* pHeader);                 //客户端象棋走棋
    void OnMsgSuccess(Player* player, MSG_HEADER* pHeader);                //客户端胜利                  //客户端说话

    void Log(QString text);            //发送日志信号的函数

private:

    QList<Player*> mPlayers;           //玩家列表
    QMutex mMutex;                     //互斥量
    QList<ROOM_STATE> states;          //房间状态列表

    int mTimerCheckHeartbeat;          //检查心跳
    int mTimerUpdateRoomState;         //通知各客户端房间人数状态
};


#endif // SERVER_H
